<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\AdminDepart;
use app\admin\model\Admin;
use fast\Tree;
use think\Db;

/**
 * 通知管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的通知
 */
class Notice extends Backend
{

    /**
     * @var \app\common\model\Notice
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Notice');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			$admin_id = $this->auth->id;
            $list = $this->model
                ->with(['sender', 'receiver'])
                ->where($where)
				->where(function($query)use($admin_id){
					$query->where('receiver_id', $admin_id);
				})
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                if($v->depart_ids)
				{
					$departs = AdminDepart::where('id', 'in', $v->depart_ids)->column('name');
					$v->departs = implode(',', $departs);
				}
				if($v->receiver_ids)
				{
					$receivers = Admin::where('id', 'in', $v->receiver_ids)->column('nickname');
					$v->receivers = implode(',', $receivers);
				}
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		
		$this->assignconfig('hasAuth',$this->auth->check('notice/add'));
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
			
			$params = $this->request->post('row/a');
			if (empty($params)) {
				$this->error(__('Parameter %s can not be empty', ''));
			}
			
			$result = false;
			Db::startTrans();
			try {
				$params['sender_id'] = $this->auth->id;
				$params['receiver_id'] = $this->auth->id;
				$depart_ids = $params['depart_ids'];
				$params['depart_ids'] = implode(',', $params['depart_ids']);
				$params['content'] = trim($params['content']);
				$params['releasetime'] = time();
				$params['readed'] = 1;
				$result = $this->model->allowField(true)->save($params);
				if($result)
				{
					$noticeData = [];
					if($params['receiver_ids'])
					{
						$receiver_ids = explode(',', $params['receiver_ids']);
					}
					elseif($params['depart_ids'])
					{
						foreach($depart_ids as $vo)
						{
							$sub_departs = AdminDepart::where('pid', $vo)->column('id');
							if($sub_departs)
							{
								$depart_ids = array_merge($depart_ids, $sub_departs);
							}
						}
						$receiver_ids = Admin::where('depart_id', 'in', $depart_ids)->where('id', '<>', 1)->column('id');
					}
					else
					{
						$receiver_ids = Admin::where('id', '<>', 1)->column('id');
					}
					
					foreach($receiver_ids as $id)
					{
						$notice = array(
							'pid' => $this->model->id,
							'sender_id' => $this->auth->id,
							'receiver_id' => $id,
							'content' => $params['content'],
							'releasetime' => time(),
							'createtime' => time(),
							'updatetime' => time()
						);
						
						$noticeData[] = $notice;
					}
					$this->model->insertAll($noticeData);
				}
				
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
			if ($result === false) {
				$this->error(__('No rows were inserted'));
			}
			$this->success('添加成功', 'index');
		}
		
		$departList = collection(AdminDepart::column('id,pid,name'))->toArray();
        Tree::instance()->init($departList);
        $departList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $departName = [];
        foreach ($departList as $k => $v) {
            $departName[$v['id']] = str_replace(['└','├'], '', $v['name']);
        }
		$this->view->assign('departList', build_select('row[depart_ids][]', $departName, [], ['title'=>"全部机构", 'class'=>'form-control selectpicker', 'multiple'=>'', 'data-rule'=>'']));
		return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		
		$row->readed = 1;
		$row->readtime = time();
		$row->save();

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
	/**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $count = $this->model->where('id', 'in', $ids)->delete();
		if ($count) {
			$this->model->where('pid', 'in', $ids)->delete();
			$this->success();
		}

        $this->error(__('No rows were deleted'));
    }
}
